#pragma once
#include<memory>
#include<mutex>
#include<condition_variable>
#include<thread>
#include"Queue.h"
class WorkThread {
public:
	using Callback = std::function<void(WorkThread*)>;
private:
	enum Status {
		UNSTART, RUNNING, EXIT,
	};

	bool isCoreThread;
	long maxSleepTime;
	shared_ptr<Queue>queue;

	Status status;
	thread thread_;

	mutex mx;
	condition_variable cond;

	Task task;

	Callback callback;

public:
	WorkThread(bool isCoreThread, long maxSleepTime, shared_ptr<Queue>queue):
		isCoreThread(isCoreThread),maxSleepTime(maxSleepTime),queue(queue), status(UNSTART), thread_(&threadFunc)
	{

	}

	void registExitCallback(Callback cb) {
		callback = cb;
	}

	void start() {
		status = RUNNING;
		cond.notify_one();
	}
	void exit() {
		status = EXIT;
	}

	bool execute(Task task) {

	}

	void threadFunc() {
		if(status== UNSTART){
			unique_lock<mutex>lock(mx);
			cond.wait_for(lock, std::chrono::milliseconds(maxSleepTime), [&]() {return status!= UNSTART; });
		}
		Task task;
		while (status==RUNNING) {
			bool flag=queue->tryPop(task, maxSleepTime);
			if (flag) {
				status = EXIT;
				break;
			}
			task();
		}
		callback(this);
	}
};
